use html_parser::{DomNode, HtmlParser, ParserConfig};
use std::env;
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 获取命令行参数
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        println!("用法: {} <HTML文件路径>", args[0]);
        return Ok(());
    }

    // 读取HTML文件
    let file_path = &args[1];
    let html = fs::read_to_string(file_path)?;

    // 配置解析器
    let config = ParserConfig {
        preserve_comments: true,
        preserve_whitespace: false,
        decode_entities: true,
        auto_fix: false,
        encoding: "utf-8".to_owned(),
        enable_i18n: true,
    };

    // 创建解析器并解析HTML
    let parser = HtmlParser::new(config);
    let dom = parser.parse(&html)?;

    // 打印DOM结构
    print_dom_structure(&dom, 0);

    // 示例：使用选择器查找元素
    if args.len() > 2 {
        let selector = &args[2];
        println!("\n使用选择器 '{}' 查找元素：", selector);

        match parser.query_selector(&dom, selector) {
            Ok(elements) => {
                println!("找到 {} 个匹配元素", elements.len());
                for (i, element) in elements.iter().enumerate() {
                    println!("{}. {:?}", i + 1, element);
                }
            }
            Err(err) => {
                println!("选择器错误: {}", err);
            }
        }
    }

    Ok(())
}

fn print_dom_structure(node: &DomNode, level: usize) {
    let indent = " ".repeat(level * 2);

    match &node.node_type {
        html_parser::NodeType::Element(tag) => {
            print!("{}Element: <{}", indent, tag);

            // 打印属性
            for attr in &node.attributes {
                print!(" {}=\"{}\"", attr.name, attr.value);
            }

            println!(">");
        }
        html_parser::NodeType::Text(text) => {
            if !text.trim().is_empty() {
                println!("{}Text: \"{}\"", indent, text.trim());
            }
        }
        html_parser::NodeType::Comment(comment) => {
            println!("{}Comment: <!-- {} -->", indent, comment);
        }
        html_parser::NodeType::Document => {
            println!("{}Document", indent);
        }
        html_parser::NodeType::DocumentType(doctype) => {
            println!("{}DocumentType: <!DOCTYPE {}>", indent, doctype);
        }
    }

    // 递归处理子节点
    for child in &node.children {
        print_dom_structure(child, level + 1);
    }
}
